gpt4 book ai didi

c++ - 类的构造函数的声明和定义并打印出私有(private)和公共(public)变量?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:51:41 27 4
gpt4 key购买 nike

我很难过,我现在正在学习 C++ 类(class),这是我遇到的问题,我必须声明和定义构造函数,我不知道我在做什么错我试过但无法得到结果请帮助

 #include <iostream>
using namespace std;

class exercise
{
public:
//declaration: constructor of class exercise
int public_var;
int get_private_var();
private:
int private_var;
};

//definition: constructor of class exercise
int exercise::get_private_var()
{
return private_var;
}

int main()
{
exercise object(2,3);
int pub_var = object.public_var;
int pri_var = object.get_private_var();
cout << pub_var <<' '<<pri_var<<endl;
return 0;
}

最佳答案

示例构造函数是:

class exercise
{
public:
exercise(int,int);
int public_var;
int get_private_var();
private:
int private_var;
};

//Constructor definition
exercise::exercise(int a, int b)
{
public_var = a;
private_var = b
}
//rest of member functions

关于c++ - 类的构造函数的声明和定义并打印出私有(private)和公共(public)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15340717/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com