如何添加到此代码中,以便它打印"b"而不删除任何内容?

How can I add to this code so it prints "b" without removing anything?

本文关键字:打印 任何内 删除 添加 何添加 代码      更新时间:2023-10-16

我用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 ;}