我知道类中的数据应该是私有(private)的,然后使用getter和setter来读取/修改它们。但是比起直接使用student.scores.push_back(100)省了一个成员函数是不是很麻烦。classStudent{public:voidaddToScores(intinScore){scores.push_back(inScore);}private:vectorscores;}简而言之,我很好奇人们实际上在做什么,总是使用getter和setter严格私有(private)数据? 最佳答案 成员函数的目的是公开接口
在C++中,如果我们有这个类classUncopyable{public:Uncopyable(){}~Uncopyable(){}private:Uncopyable(constUncopyable&);Uncopyable&operator=(constUncopyable&);};然后我们有一个派生类classDervied:privateUncopyable{};我的问题是:当编译器在派生类中生成默认的复制构造函数和赋值运算符时,为什么这不会生成编译时错误?生成的代码不会尝试访问基类私有(private)成员吗? 最佳答案
我想知道在C++程序中是否存在更改代码中的访问说明符(公共(public)/protected/私有(private))会导致该程序行为发生变化的情况? 最佳答案 模板允许您根据成员或方法是否可访问来执行不同的操作。作为一个随机示例,请考虑以下内容:#include#includestructfoo_private{private:foo_private(){}};structfoo_public{public:foo_public(){}};intmain(){std::cout::value;std::cout::value;}
我对运算符=很满意,它由编译器自动合成。但我希望它是私有(private)的,并且不想用类型的页面长定义来膨胀我的代码Foo&Foo::operator=(constFoo&foo){if(this==&foo)return*this;member1_=foo.member1_;member2_=foo.member2_;member3_=foo.member2_;...member1000_=foo.member1000_;return*this;}请问有什么办法吗? 最佳答案 在C++11中是:classFoo{Foo&oper
我试图定义这样一个类:#includeclassmy_class{private:someone_elsesfoo;public:myclass();~myclass();//...};但是编译器失败了:“someone_elses类型的字段foo有一个私有(private)的复制构造函数”。现在我知道我可以通过以下方式解决这个问题:classmy_class{private:someone_elses*foo;//...};my_class::my_class(){foo=newsomeone_elses();}my_class::~my_class(){deletefoo;}我的问
我有以下问题。我有一个带有私有(private)内部类的类。我现在想为内部类实现一个friend交换功能。但是我不知道如何制作非内联交换功能。如果我在内部类中定义它,一切正常。如果有人可以告诉我如何使其成为非内联的,我将不胜感激:)一些代码确实说明了问题:classOuter{classInner{intdata;friendswap(Inner&lhs,Inner&rhs)//whatisthesyntaxto{//makethisfunctionnoninline?usingstd::swap;swap(lhs.data,rhs.data);}}} 最佳
我有一个具有私有(private)属性的类,它是一个vector。执行getter函数的最佳方法是什么?返回整个vector:vectorgetNames(){returnnames;}这会返回一个拷贝还是一个指针?因为它是私有(private)的,所以可以访问吗?返回迭代器:vector::iteratorgetNames(){returnnames.begin();}公开载体我知道这对OOP来说是不好的做法,只是列出选项。 最佳答案 返回constvector&.它确保它不会在外部被修改并且不会制作拷贝。
我是C++的新手,我有一个关于继承中的c++protected和private成员的问题。如果一个类是public继承了一个基类,protected和private成员变量是否会成为派生类的一部分?例如:classBase{protected:inta;intb;private:intc;intd;public;intq;};classDerived:publicBase{};类Derived是否也有a,b,c,d,q的所有成员?我们可以在Derived类中将inta定义为public、protected和private吗? 最佳答案
上下文:我们正在尝试建立一个名为Operand的类模板,它可以采用多种类型作为其类型名T。.这些在以下枚举中定义:enumeOperandType{INT8INT16,INT32,FLOAT,DOUBLE};那些对应于中定义的类型,即int8_t,int16_t,等等。构造函数必须是Operand(std::stringconst&value);.templateclassOperand:publicIOperand{public:Operand(std::stringconst&value){std::stringstreamss(value);ss>>_value;//_type=
对于C类的私有(private)类成员M的延迟初始化是否有最佳实践?例如:classC{public:C();//Thisworksproperlywithoutm,andmaybecalledatanytime,//evenbeforestartWorkwascalled.someSimpleStuff();//Calledsingletime,onceparamisknownandworkcanbestarted.startWork(intparam);//Usesm.Calledmultipletimes.//GuaranteedtoonlybecalledafterstartW