美文网首页
关于类内成员变量类型绑定

关于类内成员变量类型绑定

作者: 404Not_Found | 来源:发表于2021-08-27 18:15 被阅读0次
  • 作者: 雪山肥鱼
  • 时间:20210828 17:46
  • 目的: 类内成员变量类型绑定时机

C++ 的类内也可以定义变类型

绑定成员函数返回值类型

#include <iostream>

using namespace std;

string myvar = "I love china";

class A
{
    int myfunc()
    {
        return myvar;
    }

private:
    int myvar;
};

int main(int argc, char ** argv)
{
    //编译器对 classA 整体解析完成后,再解析myfunc的。这样就和全局变量myvar 区分开来。 
    return 0;
}

返回值类型为 int,即类内的类型,编译器对class A 整体解析完成后,再分析myfunc。区分对待了 全局变量 string 类型的 myvar。

下述代码效果相同

#if 0
class A
{
    int myfunc();

private:
    int myvar;
};

int A::myfunc()
{
    cout << myvar << endl;
    //全局的
    cout << ::myvar.c_str() << endl;
    return myvar;
}

string myfunc()
{
  return myvar;//只能看到 全局变量string
}

int main(int argc, char ** argv)
{
    //效果一样的.
    return 0;
}
#endif

要想输出全局变量,则需要增加::作用域

成员函数参数变量类型

typedef string mytype;

class A
{
public:
    void myfunc(mytype tmpvalue) //string,因为此句话在 下处新定义的类型之前
    {
        m_value = tmpvalue;//报错string 类型 赋值给了 整形
    }
private:
    //观察 mytpye类型
    typedef int mytype;
    mytype m_value; // int

};

int main(int argc, char **argv)
{
    return 0;
}

定义成员变量类型 mytype (int), 同时叶定义了全局的 变量类型 mytype(string)。
在成员函数 myfunc 中,mytype 类型使用的是string

即使是如下代码

typedef string mytype;

class A
{
public:
    void myfunc(mytype tmpvalue); //string
private:
    //观察 mytpye类型
    typedef int mytype;
    mytype m_value; // int

};
//彻底报错,找不到成员函数,因为 此处 mytype 类型为 类内的int 类型。而class A 在声明的时候,是string 类型
void A::myfunc(mytype tmpvalue) // int
{
    m_value = tmpvalue; // 报错 类型不符合
}

void myfunc(mytype tmpvalue) //string 类型
{

}

int main(int argc, char **argv)
{
    //对于成员函数参数的特性
        // 是在编译器第一次遇到这个类型而决定。与成员函数返回指相反,成员函数返回指是return的时候才解析是什么类型
        // 所以 类内如果有类型定义,一定要提升到 类的开头。私有共有无所谓。
    return 0;
}

结论就像上述代码 main 函数所提。

  • 成员函数参数类型,谁离得近,变量类型就是谁的
  • 成员函数返回值类型, 整个类分析完了,才能定夺。

相关文章

网友评论

      本文标题:关于类内成员变量类型绑定

      本文链接:https://www.haomeiwen.com/subject/csabiltx.html