class Foo { public: int x; int y; Foo() { x = 1; y = 1; } Foo(int x_ = 10, int y_ = 10) { x = x_; y = y_; } void p() { int x = 20; // local variable cout << "x is " << x << " "; cout << "y is " << y << endl; } }; int main() { Foo foo; cout << x << " " << y << endl; return 0; }
时间: 2023-05-13 14:07:33 浏览: 49
在这段代码中,cout << x << " " << y << endl; 会报错,因为x和y是Foo类的成员变量,需要通过对象来访问。正确的写法应该是cout << foo.x << " " << foo.y << endl;。
相关问题
#include <iostream> using namespace std; class Foo { public: Foo(char x) { x_ = x; } char getX() const { return x_; } public: static int y_; private: char x_; }; // ERROR *********found********* int Foo.y_ = 42; int main(int argc, char *argv[]) { // ERROR *********found********* Foo f; // ERROR *********found********* cout << "X = " << f.x_ << endl; cout << "Y = " << f.y_ << endl; return 0; }
在这段代码中,有三个错误:
1. 在类 Foo 中,静态成员变量 y_ 的声明和初始化应该在类外进行,但是在声明时不应该使用 static 关键字,只需要在定义时使用即可。
2. 在 main 函数中,创建 Foo 类的对象时,需要传入一个 char 类型的参数,但是没有传入。应该修改为 Foo f('a')。
3. 在 main 函数中,输出对象的私有成员变量 x_ 和静态成员变量 y_ 时,因为这两个成员变量都是私有的,所以不能直接访问。应该使用 getX() 函数访问 x_,使用 Foo::y_ 访问 y_。
下面是修改后的代码:
```cpp
#include <iostream>
using namespace std;
class Foo {
public:
Foo(char x) { x_ = x; }
char getX() const { return x_; }
public:
static int y_;
private:
char x_;
};
// 静态成员变量 y_ 的定义和初始化
int Foo::y_ = 42;
int main(int argc, char *argv[]) {
Foo f('a');
cout << "X = " << f.getX() << endl;
cout << "Y = " << Foo::y_ << endl;
return 0;
}
```
class Foo3 {const int x;};合法吗
不合法。在定义一个类的时候,如果该类有一个 const 成员变量,则必须对其进行初始化,否则会导致编译错误。在该类中,const int x 没有被初始化,因此会编译错误。可以通过以下方式对其进行初始化:
```c++
class Foo3 {
public:
Foo3(int num):x(num){}
private:
const int x;
};
```
或者使用成员初始化列表:
```c++
class Foo3 {
public:
Foo3(int num):x(num){}
private:
const int x;
};
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)