Error to use of static and static function in C++
我是初学者的编程,开始C++的一个薄弱环节。我的静态变量的使用有问题。我在同一个问题中读到了静态变量的用法,但我只理解这辆车::countofinput;。从下面的帖子:
如何调用其他类的静态方法
C++静态成员方法调用类实例
如何从另一个类调用静态方法?
这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | #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\practise\main.cpp: In function 'void print()':
F:\CLion\practise\main.cpp:10:13: error: invalid use of non-static data member 'Car::carName'
char *carName;
^F:\CLion\practise\main.cpp:40:33: error: from this location
cout <<"Car Name:" << carName <<"\t"; ^F:\CLion\practise\main.cpp:11:12: error: invalid use of non-static data member 'Car::carNumber'
double carNumber;
^F:\CLion\practise\main.cpp:41:35: error: from this location
cout <<"Car Number:" << carNumber << endl; ^F:\CLion\practise\main.cpp: In function 'int main()':
F:\CLion\practise\main.cpp:57:16: error: 'class Car' has no member named 'print'
product[0].print();
我用克莱恩,提前谢谢。
1 | Car() : carName("X"), carNumber(0) {} |
并将EDOCX1[6]的定义放在.cpp文件(在全局范围内)的类之外:
1 | int Car::countOfInput = 0; |
(如果每次调用
哦,天哪。你有很多问题。首先,构造函数不初始化任何成员变量。
1 2 3 4 5 | Car() { static int countOfInput = 0; char carName = {'X'}; double carNumber = 0; } |
相反,它声明三个局部变量并将它们设置为值。你想要的是:
1 2 3 4 5 | Car() : carName(nullptr) , carNumber(0.0) { } |
然后,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Car() : carNumber(0.0) { } void setVal(){ cout <<"Car Name:"; cin >> carName; cout << endl <<"Car Number:"; cin >> carNumber; cout << endl; Car::countOfInput += 1; } |
接下来,你需要让
1 2 | void print() const { ... |
最后,您需要定义
1 | int Car::countOfInput = 0; |
错误消息与静态变量或静态方法无关。
关键字
正如@tuple_cat所建议的,
1 2 3 4 5 6 7 8 9 | void print() const { if(Car::countOfInput == 0){ cout <<"Error: empty!"; return; } cout <<"LIST OF CarS" << endl; cout <<"Car Name:" << carName <<"\t"; cout <<"Car Number:" << carNumber << endl; } |