如何添加到此代码中,以便它打印"b"而不删除任何内容?
How can I add to this code so it prints "b" without removing anything?
我用c ++ 11编写了这段代码:
#include <iostream>
#include <string>
using namespace std;
class A{
public:
void print() const { cout << "a" << endl; }
};
void f(const A& a){
a.print();
}
我想通过添加但不删除任何内容来编辑此代码,因此无论输入如何,它都会打印字母"b"
而不是"a"
。这怎么可能?我在互联网上没有找到答案?
使用退格键:
cout << "abb";
退格字符(b
)将光标收回,然后b
将覆盖a
。
这会增加你的代码;不会删除任何内容并打印"b":
#include <iostream>
#include <string>
using namespace std;
class A{
public:
void print() const {cout << "b" << endl;
return;
cout << "a" << endl ;}
};
void f(const A& a){
a.print();
}
将
类包装在命名空间中。然后写你自己的。命名空间是新的。您的新A班也是如此。
namespace unused {
class A{
public:
void print() const { cout << "a" << endl; }
};
}
class A{
public:
void print() const { cout << "b" << endl; }
};
void f(const A& a){
a.print();
}
@zmbq给出了一个很好的解决方案。这是我的看法。
class A{ // could make this class abstract
public:
virtual void print() const { cout << "a" << endl; }
};
class B: public A {
void print() const { cout << "b" << endl; }
};
void f(const A& a) {
a.print();
}
B b;
f(b); // it should print 'b'
这样,在函数内部f
如果传递的实例的类型为 B
,则将调用派生类的实现。
您可以使用逗号的丢弃属性
void print() const {cout << ("a", "b") << endl ;}
---编辑---
为了避免警告"逗号运算符的左操作数无效",例如,您可以将"a"
转换为(void)
void print() const {cout << ((void)"a", "b") << endl ;}
相关文章:
- 打印时有二叉树问题.用户输入不打印任何内容
- main() 中的 std::cout 在调试期间不会在调试控制台中打印任何内容
- cout 不打印任何内容到控制台
- 为什么字符串没有更新并且最终没有打印任何内容
- 我如何处理 TMP 以避免打印任何东西
- 是否有任何内置的哈希图函数来处理 c++ 中的值输入?
- 泛型函数反向打印任何矢量,编译器出错
- 是否有任何内置函数可以检查给定的两个数字在给定整数数组中的顺序是否相同?
- Cout 一个字符串可以打印任何内容到屏幕上
- "cout<<count<<endl;"没有打印任何内容
- C++ 中是否有任何内置阶乘函数?
- 为什么循环迭代不打印任何东西?
- 函数不打印任何 c++
- 下面的代码没有打印任何东西
- 我的 c++ 程序中的字符数组不会打印任何内容
- 如果否则错误:如何使其打印任何数字
- 在 C++ 中声明向量后无法打印任何内容
- 在模板功能中打印任何结构
- 如果找不到解决方案,我如何留下递归循环,而不会打印任何东西
- 是否有任何内置函数可以告诉编译器分支是否可预测