C++:私有方法返回的本地typedef

Fra*_*ois 2 c++ typedef private return-value

下面的代码不正确,我理解为什么,get_point返回类在类外未知的值:

class C {
    typedef std::pair<double, double> Point;
 public:
    Point get_point() const;
};

Point C::get_point() const {
    [...]
}
Run Code Online (Sandbox Code Playgroud)

但为什么下面的代码不正确呢?课堂外没有使用本地类型!

class C {
    typedef std::pair<double, double> Point;
 private:
    Point get_point() const;
};

Point C::get_point() const {
    [...]
}
Run Code Online (Sandbox Code Playgroud)

当我们使用时,C::我们应该在课堂内,所以我们应该可以使用Point!

Vla*_*cow 5

这是一个有效的代码.这是一个示范计划

#include <iostream>
#include <utility>

class C 
{
    typedef std::pair<double, double> Point;
    Point p { 10.10, 20.20 };
 public:
    Point get_point() const;
};

C::Point C::get_point() const { return p; }

int main() 
{
    C c;

    auto p = c.get_point();

    std::cout << p.first << ' ' << p.second << std::endl;

    std::pair<double, double> p2 = c.get_point();

    std::cout << p2.first << ' ' << p2.second << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

程序输出是

10.1 20.2
10.1 20.2
Run Code Online (Sandbox Code Playgroud)

您不仅可以使用C::Point作为类型别名的名称std::pair<double, double>.

至于这段代码

class C {
    typedef std::pair<double, double> Point;
 private:
    Point get_point() const;
};

Point C::get_point() const {
    [...]
}
Run Code Online (Sandbox Code Playgroud)

然后你必须写

C::Point C::get_point() const {
Run Code Online (Sandbox Code Playgroud)

在定义类的范围内搜索用作类定义外定义的类成员函数的返回类型的非限定名称.而且没有名字Point.您必须使用限定名称.