简体   繁体   English

使用指向成员和宏的指针

[英]Using pointers to members and macros

I'm having problems with the following code: 我在使用以下代码时遇到问题:

#include<iostream>
#include<utility>

#define Row *prow
#define Col *pcol

typedef unsigned int uint;
typedef std::pair<uint, uint> Node;

uint Node::Row = &Node::first;
uint Node::Col = &Node::second;

int main()
{
    Node node(1,2);
    std::cout << node.*prow << node.*pcol << '\n';    // OK
    std::cout << node.Row << node.Col << '\n';        // doesn't compile
}

The idea was to use std::pair but replace first and second with other names, in that case Row and Col . 想法是使用std :: pair,但用其他名称替换firstsecond ,在这种情况下为RowCol However, the last line doesn't compile even though it should be exactly the same as the line before it. 但是,即使最后一行应与前一行完全相同,也不会编译。 I'd really appreciate if someone could explain me why it happens. 如果有人能解释我为什么会发生,我将非常感谢。 I'm using VS2015. 我正在使用VS2015。

Edit: compiler error C2059 syntax error:'*' 编辑:编译器错误C2059 syntax error:'*'

.* is a single token. .*是单个令牌。 Your macro is generating two adjacent tokens, . 您的宏正在生成两个相邻的标记. and * , which is not the same thing. * ,这不是同一回事。 (Or at least it might do. Almost certainly you're invoking undefined behaviour.) (或者至少可以这样做。几乎可以肯定,您正在调用未定义的行为。)

There's probably a solution involving token pasting, but you'd do yourself a big favour (and make Bjarne happy) by just not using macros in C++. 可能存在涉及令牌粘贴的解决方案,但是您将不使用C ++中的宏就可以帮自己一个大忙(并使Bjarne开心)。

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

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