有一个界面
class abc {
public:
virtual int foo() = 0;
...
}
class concrete1: public abc {
public:
int foo() {
..
}
class concrete2 : public abc {
public:
int foo() {
..
}
}
Run Code Online (Sandbox Code Playgroud)
现在在我的主程序中,我需要根据变量的值构造类
abc *a;
if (var == 1)
a = new concrete1();
else
a = new concrete2();
Run Code Online (Sandbox Code Playgroud)
显然我不希望程序中到处都是这两行(请注意我已经简化了这里以便事情清楚).如果有的话,我应该使用什么设计模式?
如何打印字符串的位表示
std::string = "\x80";
void print (std::string &s) {
//How to implement this
}
Run Code Online (Sandbox Code Playgroud) 我有一个看起来像这样的课程
class Student {
public String str;
public int marks;
}
Run Code Online (Sandbox Code Playgroud)
说3个对象
学生S1(str:sub1,标记:10),S2(str:sub2,标记:5),S3(str:s3,标记:2)
我想确保对于Student对象,如果sub1> sub2> sub3则此条件成立,则mark1> marks2> marks3
#include "iostream"
#include "vector"
class ABC {
private:
bool m_b;
public:
ABC() : m_b(false) {}
ABC& setBool(bool b) {
m_b = b;
return *this;
}
bool getBool() const {
return m_b;
}
};
void foo(const std::vector<ABC> &vec) {
vec[0].setBool(true);
}
int main(int argc, char*argv[]) {
std::vector<ABC> vecI;
ABC i;
vecI.push_back(i);
foo(vecI);
}
Run Code Online (Sandbox Code Playgroud)
当我编译它时,我得到这个错误:const ABC
作为discards限定符的this
参数传递ABC& ABC::setBool(bool)
任何想法为什么会发生这种情况,因为对象本身并不是一个常数.
使用案例:
class B {
int b;
public:
int getB() {
return b;
}
};
class A {
B *b;
public:
int getB() {
if (b ) { //How can I avoid the null check for b here
return b->getB();
}
}
}
Run Code Online (Sandbox Code Playgroud)