简体   繁体   English

派生类成员函数在C ++中失败

[英]derived class member function failed in c++

To make long story short: 简而言之:

class A {
        public:
              A();
              ~A();
              void SetID(char* ID);
              char* GetID();
        protected:
              char ID[10];
};

class B: public A {
        public:
              B();
              ~B();
        protected:
              ...
        private:
              ...
};

Then in main: 然后在主要:

 ...
 B *temp = new B;
 temp->SetID("0x12345678");
 ...

Then the compiler said "Expected constructor,destructor or type conversion before -> token" where "temp->SetID("0x12345678")" lies 然后,编译器说“->标记之前的预期构造函数,析构函数或类型转换”,其中“ temp-> SetID(“ 0x12345678”)”位于

Anyone gimme some hints?? 有人给我一些提示吗?

Whole Program as Loki suggested: Loki建议整个程序:

  #include <iostream>

  using namespace std;

  class A {
      public:
         A();
         ~A();
         void SetID(char* id);
         char* GetID();
       protected:
            char ID[10];
   };

   void A::SetID(char* id){
         strcpy(ID,id);          
    }
    char* A::GetID(){
         return ID;
    }
    class B: public A {
             public:
                 B();
                ~B();
             protected:
                int num;
     };


    int main(){
    B *temp = new B;
    B->SetID("0x12345678");
    cout<<B->GetID()<<endl;

    return 0;
    }

You are using B , which is a type, where you probably meant to use temp which is the name of the variable. 您正在使用B ,它是一种类型,您可能打算使用temp ,它是变量的名称。

Instead of: 代替:

int main(){
B *temp = new B;
B->SetID("0x12345678");
cout<<B->GetID()<<endl;

return 0;
}

You probably meant: 您可能的意思是:

int main(){
B *temp = new B;
temp->SetID("0x12345678");
cout<<temp->GetID()<<endl;

return 0;
}

which is more like the "excerpt" that you posted. 这更像是您发布的“节选”。

Let me guess. 让我猜猜。

You have closed main by an unpaired curly brace before you got to this code that you believe is in main . 在获得您认为位于main代码之前,您已经用不成对的花括号将main关闭。 So it is outside of any function, and that is no place for expressions other than initializers. 因此它在任何函数的外部,除了初始化程序之外,该表达式不存在其他位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM