如果我写这个程序:
#include <iostream>
namespace foo {
struct bar {
int x;
};
}
int main (void) {
struct foo::bar *a = new struct foo::bar;
delete a;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
并编译它:
g++ main.cxx -Wall -Wextra
Run Code Online (Sandbox Code Playgroud)
它给了我这个警告:
main.cxx: In function ‘int main()’:
main.cxx:10:39: warning: declaration ‘struct foo::bar’ does not declare anything [enabled by default]
Run Code Online (Sandbox Code Playgroud)
但是,如果我在struct关键字后面取出new关键字:
#include <iostream>
namespace foo {
struct bar {
int x;
};
}
int main (void) {
struct foo::bar *a = new foo::bar;
delete …Run Code Online (Sandbox Code Playgroud) 假设我有一个带有虚函数的类和一个以不同方式实现虚函数的派生类.假设我还有一个用于存储派生类的基类向量.如何在不事先知道派生类是什么的情况下,在向量中执行派生类的虚函数?说明问题的最小代码:
#include <iostream>
#include <vector>
class Foo {
public:
virtual void do_stuff (void) {
std::cout << "Foo\n";
}
};
class Bar: public Foo {
public:
void do_stuff (void) {
std::cout << "Bar\n";
}
};
int main (void) {
std::vector <Foo> foo_vector;
Bar bar;
foo_vector.resize (1);
foo_vector [0] = bar;
bar.do_stuff (); /* prints Bar */
foo_vector [0].do_stuff (); /* prints Foo; should print Bar */
return 0;
}
Run Code Online (Sandbox Code Playgroud)