抽象函数和虚函数有什么区别?在哪些情况下建议使用虚拟或抽象?哪一个是最好的方法?
我从ReSharper收到一条关于从我的对象构造函数调用虚拟成员的警告.
为什么不做这件事?
我正在学习C++而我正在进入虚拟功能.
根据我的阅读(在书中和在线),虚函数是基类中的函数,您可以在派生类中重写它们.
但是在本书前面,当我学习基本继承时,我能够在不使用的情况下覆盖派生类中的基本函数virtual.
那我在这里错过了什么?我知道虚拟功能还有更多功能,而且它似乎很重要,所以我想清楚它究竟是什么.我在网上找不到直接答案.
假设我有课程Foo并Bar设置如下:
class Foo
{
public:
int x;
virtual void printStuff()
{
std::cout << x << std::endl;
}
};
class Bar : public Foo
{
public:
int y;
void printStuff()
{
// I would like to call Foo.printStuff() here...
std::cout << y << std::endl;
}
};
Run Code Online (Sandbox Code Playgroud)
正如在代码中注释的那样,我希望能够调用我所覆盖的基类函数.在Java中有super.funcname()语法.这在C++中是否可行?
我听说C++类成员函数模板不能是虚拟的.这是真的?
如果它们可以是虚拟的,那么一个人可以使用这样一个函数的场景的例子是什么?
假设我有两个C++类:
class A
{
public:
A() { fn(); }
virtual void fn() { _n = 1; }
int getn() { return _n; }
protected:
int _n;
};
class B : public A
{
public:
B() : A() {}
virtual void fn() { _n = 2; }
};
Run Code Online (Sandbox Code Playgroud)
如果我写下面的代码:
int main()
{
B b;
int n = b.getn();
}
Run Code Online (Sandbox Code Playgroud)
人们可能期望将n其设置为2.
事实证明,n设置为1.为什么?
使用下面给出的结构定义......
struct A {
virtual void hello() = 0;
};
Run Code Online (Sandbox Code Playgroud)
方法#1:
struct B : public A {
virtual void hello() { ... }
};
Run Code Online (Sandbox Code Playgroud)
方法#2:
struct B : public A {
void hello() { ... }
};
Run Code Online (Sandbox Code Playgroud)
这两种覆盖hello函数的方法有什么区别吗?
据我所知,override在C++ 11中引入关键字只不过是一个检查,以确保正在实现override的virtual函数是基类中的函数.
是吗?
当我收到代码评论评论说虚拟功能不需要内联时,我收到了这个问题.
我认为在直接在对象上调用函数的场景中,内联虚函数可以派上用场.但是我想到的反驳论点是 - 为什么要想定义虚拟然后使用对象来调用方法呢?
最好不要使用内联虚拟功能,因为它们几乎从未扩展过吗?
我用于分析的代码片段:
class Temp
{
public:
virtual ~Temp()
{
}
virtual void myVirtualFunction() const
{
cout<<"Temp::myVirtualFunction"<<endl;
}
};
class TempDerived : public Temp
{
public:
void myVirtualFunction() const
{
cout<<"TempDerived::myVirtualFunction"<<endl;
}
};
int main(void)
{
TempDerived aDerivedObj;
//Compiler thinks it's safe to expand the virtual functions
aDerivedObj.myVirtualFunction();
//type of object Temp points to is always known;
//does compiler still expand virtual functions?
//I doubt compiler would be this much intelligent!
Temp* pTemp = &aDerivedObj;
pTemp->myVirtualFunction();
return …Run Code Online (Sandbox Code Playgroud) c++ ×8
overriding ×4
constructor ×3
abstract ×1
c# ×1
c++-faq ×1
c++11 ×1
inheritance ×1
inline ×1
oop ×1
resharper ×1
templates ×1
warnings ×1