【发布时间】:2016-09-11 09:08:04
【问题描述】:
我是编程初学者,刚开始学 C++。我在使用我的静态变量时遇到问题。我在各种相同的问题中阅读了有关使用静态变量的信息,但我只了解这个 Car::countOfInput;。来自下面的帖子:
这是我的代码:
#include <iostream>
#include <conio.h>
#include <string.h>
using namespace std;
class Car{
private:
static int countOfInput;
char *carName;
double carNumber;
public:
Car() {
static int countOfInput = 0;
char carName = {'X'};
double carNumber = 0;
}
void setVal(){
double number;
cout << "Car Name: ";
char* str = new char[strlen(str) + 1];
cin>>str;
strcpy(carName, str);
cout << endl << "Car Number: ";
cin >> number; cout << endl;
carNumber = number;
Car::countOfInput += 1;
}
friend void print(){
if(Car::countOfInput == 0){
cout << "Error: empty!";
return;
}
cout << "LIST OF CarS" << endl;
cout << "Car Name: " << carName << "\t";
cout << "Car Number: " << carNumber << endl;
} const
void setCarNumber(int x){carNumber = x;}
int getCarNumber(){return carNumber;}
void setcarName(char x[]){strcpy(carName, x);}
char getcarName(){return *carName;}
int getCountOfInput(){return countOfInput;}
void setCountOfInput(int x){countOfInput = x;}
};
int main(){
Car product[3];
product[0].setVal();
product[0].print();
getch();
return 0;
}
当我运行这个时:
F:\CLion\practice\main.cpp: 在函数'void print()'中:
F:\CLion\practice\main.cpp:10:13:错误:非静态数据成员“Car::carName”的使用无效 字符 *汽车名称; ^
F:\CLion\practice\main.cpp:40:33: 错误:来自这个位置 cout
F:\CLion\practice\main.cpp:11:12: 错误:非静态数据成员 'Car::carNumber' 的使用无效 双车号; ^
F:\CLion\practice\main.cpp:41:35: 错误:来自这个位置 cout
F:\CLion\practice\main.cpp:在函数'int main()'中:
F:\CLion\practice\main.cpp:57:16: 错误:'class Car' 没有名为 'print' 的成员 产品[0].print();
我使用 CLion,提前致谢。
【问题讨论】:
-
如果一个类变量被标记为
static,它不会与它的类的任何实例相关联。你确定这就是你想要的吗? -
粗略地说,我想在每次
setVal()函数调用时增加静态变量的 count。 -
我认为您需要采取更小的步骤。您在这里构建了至少四个单独的错误 - 编写更少的代码和更早的测试会简化这一点。
标签: c++ static static-methods clion non-static