我知道Java并且我现在正在学习c ++。我比其他语言更容易学习它具有很多相同的东西。我的问题是在一本书的课上有完整的构造函数,但我在任何地方都没有面对默认的构造函数。构造函数,如果是的话,我应该写它吗?除了,我想测试什么,该类上有public:
并在其下有变量,一段时间后有private:
并在其下有也有一些变量,例如java的public和private变量?但是我们不是在C ++上写private int numbers;
private:
int numbers;
int coffee;
我对吗?
最佳答案
至少可以说,您的老师正在标记不包括默认构造函数的事实很有趣。
作为通用原则,在Java和C ++中,构造函数负责将对象初始化为完全形成的状态。之所以要使用默认构造函数,是因为可以在没有任何明确输入的情况下构造一个完整的对象。但这可能会变得很奇怪:
//Java
public class Student {
public String name;
public int age;
public Student() {
this("", 0);
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
//C++
class Student {
public: //Everything after this point has 'public' access modifier; is like putting
//'public' in front of each variable and method
std::string name;
int age;
Student() : Student("", 0) {}
Student(std::string name, int age) : name(std::move(name)), age(age) {}
};
在此示例中,
Student
具有用于使用提供的值初始化对象的构造函数,以及用于将对象初始化为具有空名称和年龄0的默认构造函数。但是想想:这有意义吗?有效的
Student
对象没有名称是否有意义,或者如果您不知道其名称,则可以构造一个Student
对象吗?暂时忘记功能要求(即,如果对象没有默认构造函数,则数组可能很难构造),逻辑上不一致的是,没有这样的输入就可以构造对象。根据您的用例,没有默认构造函数可能更有意义。因此,确定是否在代码中包含Default-Constructor是设计原则,与您使用的是Java还是C ++或大多数编程语言无关。
关于您的其他问题:
public:
,protected:
和private:
的规则与Java中的规则不同(public
和private
大多相同,protected
是单数,而Java的default
不存在在C ++中,但可以通过使用friend
关键字进行模拟),但是它们的行为很容易识别:class example {
//private:
//'class' declarations have everything 'private' by default, 'struct' makes things 'public' by default
int val; //is private
std::string type; //is private
public: //Will be public until another access modifier is used
example() {} //is public
example(int val, std::string type) : val(val), type(std::move(type)) {} //is public
void do_something() { //is public
private_function();
}
private: //Will be private until another access modifier is used
void private_function() { //is private
val++;
}
};
在Java中,您将编写如下相同的代码:
public class example {
private int val;
private String type;
public example() {}
public example(int val, String type) {
this.val = val;
this.type = type;
}
public void do_something() {
private_function();
}
private void private_function() {
val++;
}
}
关于c++ - 构造函数的默认公共(public)和私有(private)变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45943574/