我正在练习一个重要的测验,我发现了 20 个关于 c++ 的问题,我不太确定。他们没有答案,我想知道你是否可以帮我回答他们,因为我还是一个正在学习的菜鸟。我用箭头标记了我认为对于每个问题都是正确的答案,并给出了简短的理由。
问题 1
class Base{
protected:
int a;
public:
void seta(int x){a = x;};
void printa(void){cout << a;};
};
class SecondClass : public Base
{
public;
int b;
};
void main (void)
{
Secondclass tmp;
tmp.seta(12);
tmp.printa();
}
a)SecondClass.a is public;
b)SecondClass.a is protected; <-- (Since SecondClass inherits from Base)
c)SecondClass.a is private;
d)SecondClass.a is not accessible;
问题2
执行下面的函数 foo() 会发生什么?假设 bar() 是一个现有函数。
void foo()
{
Object *o = new Object;
bar(o);
}
a) o is destroyed at the end of the scope of foo
b) o is not destroyed <-- (since there is no delete and o is a pointer)
c) o is destroyed if there is no exception in bar()
d) None of the above
问题 3
考虑头文件中的以下函数声明:
void doit(char *, int);
int doit(char *);
float doit(float, float);
Which of the following declarations cannot follow in the same header (no idea):
a) void doit(int, char*);
b) float doit(char *);
c) int doit(int, int);
d) int doit(int);
问题 4
抽象类中存在什么使其抽象?
a) virtual keyword prefix o member function
b) virtual keyword prefixed to member function and sufixed with =0 <--(since without the =0 it wouldnt be a pure virtual method which must be overriden)
c) member function in protected mode
d) any of the above
问题 5
下面执行代码片段的结果是什么?
//suitable #includes
class Text
{
public:
Text(const std::string &text):data(new char[text.size()+1000]){
std::copy(text.begin(),text.end(),data);
}
~Text(){
delete [] data;
}
void print() const{
std::cout << data << std::endl;
}
private:
char *data;
};
int main(int, char *[])
{
Text outer("hello");
{
const Text inner("world");
outer = inner;
}
outer.print();
return 0;
}
(No idea abou the answer)
a) prints "world", but there is a buffer overflow in the constructor
b) prints "world", no problems anywhere
c) prints "hello"
d) none of the above